package com.scqzy.shengchunqiang.sword2offer.day06;

import com.scqzy.shengchunqiang.structure.TreeNode;

import java.util.*;

/**
 * @Description:
 * @Author 盛春强
 * @Date 2021/8/14 0:48
 */
public class LevelOrder3 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (Objects.isNull(root)) {
            return Collections.emptyList();
        }
        Deque<TreeNode> deque = new ArrayDeque<>();
        List<List<Integer>> list = new ArrayList<>();
        List<Integer> child = new ArrayList<>();
        boolean rev = false;
        deque.offer(root);
        while (!deque.isEmpty()) {
            int size = deque.size();
            child = new ArrayList<>();
            while (size > 0) {
                TreeNode poll = deque.poll();
                child.add(poll.val);
                if (Objects.nonNull(poll.left)) {
                    deque.offer(poll.left);
                }
                if (Objects.nonNull(poll.right)) {
                    deque.offer(poll.right);
                }
                --size;
            }
            if (rev) {
                Collections.reverse(child);
            }
            rev = !rev;
            list.add(child);
        }
        return list;
    }
}
